// src/stores/auth.ts
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import type { User, LoginData, RegisterData, AuthResponse } from "@/types";
import { authApi } from "@/api";

export const useAuthStore = defineStore(
  "auth",
  () => {
    // State
    const user = ref<User | null>(null);
    const token = ref<string | null>(localStorage.getItem("token"));
    const loading = ref(false);
    const error = ref<string | null>(null);

    // Getters
    const isLoggedIn = computed(() => !!token.value);
    const isAdmin = computed(() => user.value?.roles?.includes("admin"));
    const userInitials = computed(() => {
      if (!user.value?.username) return "";
      return user.value.username.charAt(0).toUpperCase();
    });

    // Actions
    const login = async (credentials: LoginData) => {
      loading.value = true;
      error.value = null;

      try {
        const response: AuthResponse = await authApi.login(credentials);

        // 更新状态
        user.value = response.user;
        token.value = response.token;

        // 持久化
        if (credentials.rememberMe) {
          localStorage.setItem("token", response.token);
        } else {
          sessionStorage.setItem("token", response.token);
        }

        // 设置自动刷新token的逻辑
        if (response.expiresIn) {
          setTimeout(refreshToken, response.expiresIn * 1000 - 60000); // 提前1分钟刷新
        }

        return response;
      } catch (err) {
        error.value = err instanceof Error ? err.message : "登录失败";
        throw err;
      } finally {
        loading.value = false;
      }
    };

    const register = async (userData: RegisterData) => {
      loading.value = true;
      error.value = null;

      try {
        const response: AuthResponse = await authApi.register(userData);

        // 注册后自动登录
        user.value = response.user;
        token.value = response.token;
        localStorage.setItem("token", response.token);

        return response;
      } catch (err) {
        error.value = err instanceof Error ? err.message : "注册失败";
        throw err;
      } finally {
        loading.value = false;
      }
    };

    const logout = () => {
      // 清除状态
      user.value = null;
      token.value = null;

      // 清除存储
      localStorage.removeItem("token");
      sessionStorage.removeItem("token");

      // 调用API注销
      authApi.logout().catch((err) => {
        console.error("注销API调用失败:", err);
      });
    };

    const refreshToken = async () => {
      if (!token.value) return;

      try {
        const response = await authApi.refreshToken(token.value);
        token.value = response?.token;
        localStorage.setItem("token", response.token);

        if (response.expiresIn) {
          setTimeout(refreshToken, response.expiresIn * 1000 - 60000);
        }
      } catch (err) {
        console.error("刷新token失败:", err);
        logout(); // 刷新失败则注销
      }
    };

    const loadUserFromStorage = () => {
      const storedToken =
        localStorage.getItem("token") || sessionStorage.getItem("token");
      if (storedToken) {
        token.value = storedToken;
        // 如果有token但没有用户信息，尝试获取用户信息
        if (!user.value) {
          fetchUserProfile();
        }
      }
    };

    const fetchUserProfile = async () => {
      if (!token.value) return;

      try {
        const userProfile = await authApi.getUserInfo();
        user.value = userProfile;
      } catch (err) {
        console.error("获取用户信息失败:", err);
        logout(); // 获取失败则注销
      }
    };

    // 初始化时加载用户信息
    loadUserFromStorage();

    return {
      // State
      user,
      token,
      loading,
      error,

      // Getters
      isLoggedIn,
      isAdmin,
      userInitials,

      // Actions
      login,
      logout,
      register,
      refreshToken,
      fetchUserProfile,
      loadUserFromStorage,
    };
  },
  {
    // 持久化配置
    persist: true,
  }
);
